from threading import Semaphore
from collections import defaultdict
# 并发限制：每个用户最多允许 2 个同时请求
USER_CONCURRENCY_LIMIT = 9

# 存储每个用户的信号量（信号量初始值是并发限制值）
# user_semaphores = defaultdict(lambda: Semaphore(USER_CONCURRENCY_LIMIT))
user_semaphores = defaultdict(lambda :Semaphore(USER_CONCURRENCY_LIMIT))

def acquire_user_slot(user_id: str) -> bool:
    return user_semaphores[user_id].acquire(blocking=False)

def release_user_slot(user_id: str):
    user_semaphores[user_id].release()